package com.hotel.auth.controller;

import com.hotel.auth.service.JwtService;
import com.hotel.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/tokens/auth", "/api/token"})
/**
 * auth-service当前控制器路径是/token/auth（你之前改成了这个），而Feign走的是/tokens/auth/generate，因此返回404。
 */
@Validated
public class AuthController {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.access-token-ttl-minutes:60}")
    private long accessTokenTtlMinutes;

    // 仅负责生成单一JWT
    @PostMapping(value = "/generate", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> generate(@RequestBody Map<String, Object> body) {
        Long userId = Long.valueOf(body.get("userId").toString());
        @SuppressWarnings("unchecked")
        List<String> permissions = (List<String>) body.getOrDefault("permissions", java.util.Collections.emptyList());
        String token = jwtService.generateAccessToken(userId, permissions);
        // 将生成的 token 写入 Redis，设置与访问令牌一致的过期时间
        String key = "auth:token:" + token;
        stringRedisTemplate.opsForValue().set(key, String.valueOf(userId), accessTokenTtlMinutes, TimeUnit.MINUTES);
        return Result.success(token);
    }
}


